import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
import store from '@/store/store'
import * as types from '@/store/mutation-types'

// config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

service.interceptors.request.use(
  config => {
    // 判断是否存在token，如果存在将每个页面header都添加token
    let reg = new RegExp('(^| )user=([^;]*)(;|$)')
    let token = document.cookie.match(reg)
    if (token) {
      config.headers.common['token'] = token[2]
    }
    // config.headers.common['token'] = 'nyyj'
    if (config.method === 'post' && config.headers['Content-Type'] !== 'application/json;charset=utf-8') {
      config.transformRequest = function (data) {
        return qs.stringify(data)
      }
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (response.status === 200 && response.request.readyState === 4 && response.config.responseType === 'arraybuffer') {
      return res
    }
    if (res.code !== '200000') {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      if (res.code === '10007') {
        store.commit(types.DEL_USER)
        location.reload()
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
